package com.heatup.apt.api.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.heatup.apt.api.service.CoachCommentService;
import com.heatup.apt.api.service.CourseService;
import com.heatup.apt.api.service.CourseSignService;
import com.heatup.apt.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.JsonUtils;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.coach.CoachUserInfo;
import com.heatup.apt.model.course.CourseInfo;
import com.heatup.apt.model.user.UserInfo;

@RequestMapping(value = "/sign")
@Controller
public class CourseSignInOrOutController extends BaseController {
	public static final Logger logger = LoggerFactory.getLogger(CourseSignInOrOutController.class);

	@Autowired
    private CourseSignService courseSignService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
	private CoachCommentService coachCommentService;
    
    @Autowired
    private CourseService courseService;
    
	@RequestMapping(value = "/getUserCourseList")
    @ResponseBody
    public String getUserCourseInfo(HttpServletRequest request) {
    	ApiResultModel<CoachUserInfo> apiResultModel = new ApiResultModel<CoachUserInfo>();
    	String callback = RequestTools.RequestString(request, "callback", "");
    	boolean isLogined = isLogined();
        if (!isLogined) {
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
        } 
    	int userId = RequestTools.RequestInt(request, "userId", 0);
    	int courseId = RequestTools.RequestInt(request, "courseId", 0);
    	Integer orderId = RequestTools.RequestInt(request, "orderId", 0);
    	
    	CoachUserInfo coachModel = new CoachUserInfo();
    	//根据课程id查询课程详细信息
        CourseInfo ci = courseService.getCourseInfoById(courseId);
        if(ci == null){
        	 apiResultModel.setErrorCode(ErrorCodeConstants.Code.SECRET_ERROR_EXCEPTION.getCode());
             apiResultModel.setMsg("课程查询异常");
             return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
        }
        UserInfo userInfo = userService.getUserInfoById(userId);
        //签到未销课的课程
        List<Map<String, Object>> noSignList = courseSignService.queryUserCourseInfo(userId, courseId, 0, orderId);
        //已经销课的课程
        List<Map<String, Object>> coachList = courseSignService.queryUserCourseInfo(userId, courseId, 1, orderId);
    	if(orderId == null || orderId == 0) {
    		 apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_ORDER_ID_NULL.getCode());
             apiResultModel.setMsg(ErrorCodeConstants.Code.COURSE_ORDER_ID_NULL.getMessage());
             return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
    	}
    	Map<String, Object> oiMap= courseService.getPrice(orderId);
    	if(oiMap == null) {
   		 	apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_ORDER_ID_NULL.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.COURSE_ORDER_ID_NULL.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
    	}
    	coachModel.setAmount(oiMap.get("amount").toString());//实付金额
    	coachModel.setPrime_price(oiMap.get("prime_price").toString());
//        //如果 总共课时 不等于已上课时  就只能让用户先签到 再销课
//        if(noSignList != null && noSignList.size() < 1 && ci.getPeriods() != coachList.size()) {
//        	apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_ORDER_ID_NULL.getCode());
//            apiResultModel.setMsg("请先让学员签到！");
//            return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
//        }
        coachModel.setNoSignList(noSignList);
        coachModel.setCoachList(coachList);
        coachModel.setTotleCourse(ci.getPeriods());
        coachModel.setCourseName(ci.getTitle());
        coachModel.setHeadImg(userInfo.getHeadImg());
        coachModel.setMobile(userInfo.getMobile());
        coachModel.setNickName(userInfo.getNickName());
        coachModel.setLessCourse(ci.getPeriods() - coachList.size());
        apiResultModel.setData(coachModel);
        apiResultModel.setLogined(isLogined);
        return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
    }
	
    /**
	 * 销课
	 * <P>Author : lusa </P>      
	 * <P>Date : 2016年10月21日 </P>
	  * @param num 课程顺序
	 * @param id 签到ID
	 * @param courseId 课程ID
	 * @param storeId 门店ID
	 * @param startTime 开始时间
	 * @param closeTime 关闭时间
	 * @return
	 * @see com.heatup.apt.management.service.order.OrderService#updateCancelCourse(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@RequestMapping(value = "/close_course")
    @ResponseBody
	public String closeCourse(HttpServletRequest request) {

		ApiResultModel apiResultModel = new ApiResultModel(isLogined());
		String callback = RequestTools.RequestString(request, "callback", "");
		String storeIdTemp = RequestTools.RequestString(request, "storeId", "");
		String idTemp = RequestTools.RequestString(request, "id", "");//对应的签到id
		String closeTimeTemp = RequestTools.RequestString(request, "closeTime", "");
		String comment = RequestTools.RequestString(request, "comment", "");
		String serviceIds = RequestTools.RequestString(request, "serviceIds", "");
		String startTimeTemp = RequestTools.RequestString(request, "startTime", "");
		String num = RequestTools.RequestString(request, "num", "");
		String courseId = RequestTools.RequestString(request, "courseId", "");
		String userId = RequestTools.RequestString(request, "userId", "");//用户id
		String orderId = RequestTools.RequestString(request, "orderId", "");
		Integer courseIdInt = StringUtils.isBlank(courseId) ? 0 : Integer.parseInt(courseId);
		Integer userIdInt = StringUtils.isBlank(userId) ? 0 : Integer.parseInt(userId);
		//教练评论
		if(StringUtils.isNotBlank(comment) || StringUtils.isNotBlank(serviceIds)) {
			coachCommentService.insertCommentInfo(comment, userIdInt, courseIdInt, serviceIds, getUserId());
		}
		Date closeDate = null;
		Date startTime = null;
		try {
			startTime = DateUtils.toDateTime(startTimeTemp);
			closeDate = DateUtils.toDateTime(closeTimeTemp);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error( e.toString() + e.getCause());
		}
        if (storeIdTemp != null && idTemp != null) {
//        	updateCancelCourse(String num, String id, String courseId,
//        			String storeId,String orderId,String startTime, String closeTime,Integer userId)
            int count = 0;
			try {
				count = courseSignService.updateCancelCourse(num, idTemp,courseId, storeIdTemp,orderId, startTimeTemp, closeTimeTemp, getUserId());
			} catch (Exception e) {
				logger.error(e.getMessage() + e.toString());
			}
            if (count > 0) {
                apiResultModel.setMsg("销课成功！");
                apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            } else {
                apiResultModel.setMsg("销课失败！");
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
            }
        } else {
            apiResultModel.setMsg("入参数据异常！");
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
        }

        return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
	}
	
	
	/**
	 * 下载图片
	 */
	@RequestMapping(value = "/down_img")
    @ResponseBody
	public String downLoadPic(HttpServletRequest request) {
		String serviceIds = RequestTools.RequestString(request, "serviceIds", "");
		logger.info("serviceIds value is : " +serviceIds);
		String callback = RequestTools.RequestString(request, "callback", "");
		List<String> list = coachCommentService.getImgFromWx(serviceIds);
		logger.info("上传图片地址：" + list.toString());
		ApiResultModel apiResultModel = new ApiResultModel(isLogined());
		apiResultModel.setData(list);
		return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
	}
	
	
}
